<!-- Modal.vue -->
<template>
    <div v-if="modelValue" class="modal-mask">
      <div class="modal-container">
        <div class="modal-header">
          <text>{{ title }}</text>
          <!-- <button class="close-btn" @click="closeModal">&times;</button> -->
        </div>
  
        <div class="modal-body">
          <slot></slot>
        </div>
  
        <div class="modal-footer">
          <slot name="footer">
            <button class="confirm-btn" @click="handleConfirm">确定</button>
            <button class="cancel-btn" @click="handleCancel">取消</button>
          </slot>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { watch } from 'vue'
  
  const props = defineProps({
    modelValue: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: '提示'
    }
  })
  
  const emit = defineEmits(['update:modelValue', 'confirm', 'cancel'])
  
  // 关闭弹窗
  const closeModal = () => {
    emit('update:modelValue', false)
  }
  
  // 确认操作
  const handleConfirm = () => {
    emit('confirm')
    closeModal()
  }
  
  // 取消操作
  const handleCancel = () => {
    emit('cancel')
    closeModal()
  }
  
  // 监听 ESC 按键
  const handleKeydown = (e) => {
    if (e.key === 'Escape' && props.modelValue) {
      closeModal()
    }
  }
  
  // 添加/移除全局事件监听
  watch(() => props.modelValue, (val) => {
    if (val) {
      window.addEventListener('keydown', handleKeydown)
    } else {
      window.removeEventListener('keydown', handleKeydown)
    }
  })
  </script>
  
  <style scoped>
  .modal-mask {
    position: fixed;
    z-index: 9998;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .modal-container {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33);
    min-width: 400px;
    max-width: 80%;
  }
  
  .modal-header {
    padding: 9px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .modal-body {
    padding: 20px;
    max-height: 60vh;
    overflow: auto;
  }
  
  .modal-footer {
    padding: 9px;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  
  .close-btn {
    border: none;
    background: none;
    font-size: 24px;
    cursor: pointer;
    padding: 0 8px;
  }
  
  .close-btn:hover {
    color: #666;
  }
  
  .confirm-btn, .cancel-btn {
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
  }
  
  .confirm-btn {
    background: #409eff;
    color: white;
    border: none;
  }
  
  .confirm-btn:hover {
    background: #66b1ff;
  }
  
  .cancel-btn {
    background: white;
    border: 1px solid #ddd;
  }
  
  .cancel-btn:hover {
    background: #f5f5f5;
  }
  </style>